<script setup lang="ts">
import { ref, computed, nextTick } from "vue";
import type {
  LoginForm,
  RegisterForm,
  ForgotPasswordForm,
} from "../types/auth";
import { login, register } from "../services/authService";
import { useToast } from "vue-toastification";
import router from "../router";
import { useUserStore } from "../store/modules/user";

// 定义模态框类型
type AuthDialogType =
  | "login"
  | "register-intro"
  | "register-form"
  | "forgot-password";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  dialogType: {
    type: String as () => AuthDialogType,
    default: "login",
  },
});

const emit = defineEmits(["update:modelValue", "update:dialogType"]);

const toast = useToast();
const loading = ref(false);

// 表单数据
const loginForm = ref<LoginForm>({
  account: "",
  password: "",
  nickname: "",
});

const registerIntroVisible = ref(false);
const registerForm = ref<RegisterForm>({
  account: "",
  password: "",
  confirmPassword: "",
  nickname: "",
});

const forgotPasswordForm = ref<ForgotPasswordForm>({
  account: "",
  question: "你的出生日期?",
  answer: "",
});

// 安全问题选项
const securityQuestions = ref([
  "你的出生日期?",
  "你母亲的姓名?",
  "你的宠物名字?",
  "你的小学名称?",
  "你最喜欢的颜色?",
]);

// 计算属性获取当前对话框状态
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const currentType = computed({
  get: () => props.dialogType,
  set: (value) => emit("update:dialogType", value),
});

// 关闭对话框
const closeDialog = () => {
  visible.value = false;
  resetForms();
};

// 重置所有表单
const resetForms = () => {
  loginForm.value = { account: "", password: "", nickname: "" };
  registerForm.value = {
    account: "",
    password: "",
    confirmPassword: "",
    nickname: "",
  };
  forgotPasswordForm.value = {
    account: "",
    question: "你的出生日期?",
    answer: "",
  };
};

// 打开指定类型的对话框
const openDialog = (type: AuthDialogType) => {
  currentType.value = type;
  visible.value = true;
};

const handleLogin = async () => {
  if (!validateLoginForm()) return;

  try {
    loading.value = true;
    const response = await login(loginForm.value);

    // 存储登录信息
    const userStore = useUserStore();
    console.log(response.data);
    userStore.loginSuccess(response.data);
    console.log(userStore.currentUser?.nickname);

    toast.success("登录成功");
    closeDialog();

    console.log("即将导航到 /main");
    router
      .push("/main")
      .then(() => {
        console.log("导航到 /main 成功");
      })
      .catch((error) => {
        console.error("导航到 /main 失败", error);
        // 备选方案：强制刷新
        window.location.href = "/main";
      });
  } catch (error) {
    toast.error("登录失败，请检查账号密码");
    console.error("登录失败", error);
  } finally {
    loading.value = false;
  }
};

// 处理注册
const handleRegister = async () => {
  if (!validateRegisterForm()) return;

  try {
    loading.value = true;
    const response = await register({
      account: registerForm.value.account,
      password: registerForm.value.password,
      nickname: registerForm.value.nickname,
      confirmPassword: "",
    });
    toast.success("注册成功");
    closeDialog();
  } catch (error) {
    toast.error("注册失败，请稍后再试");
    console.log("handleRegister:", error);
  } finally {
    loading.value = false;
  }
};

// 处理忘记密码
const handleForgotPassword = () => {
  // 这里调用忘记密码接口
  toast.success("密码重置链接已发送到您的邮箱");
  closeDialog();
};

// 表单验证
const validateLoginForm = () => {
  if (!loginForm.value.account) {
    toast.error("请输入账号");
    return false;
  }

  if (!loginForm.value.password) {
    toast.error("请输入密码");
    return false;
  }

  return true;
};

const validateRegisterForm = () => {
  // 1. 验证昵称（新增）
  if (!registerForm.value.nickname) {
    toast.error("请输入昵称");
    return false;
  }

  // 2. 昵称长度限制（可选）
  if (registerForm.value.nickname.length < 2) {
    toast.error("昵称长度至少为2个字符");
    return false;
  }

  // 3. 验证账号
  if (!registerForm.value.account) {
    toast.error("请输入账号");
    return false;
  }

  // 4. 验证密码
  if (!registerForm.value.password) {
    toast.error("请输入密码");
    return false;
  }

  // 5. 验证密码复杂度（可选）
  if (registerForm.value.password.length < 6) {
    toast.error("密码长度至少为6个字符");
    return false;
  }

  // 6. 验证密码匹配
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    toast.error("两次输入的密码不一致");
    return false;
  }

  return true;
};

const validateForgotPasswordForm = () => {
  if (!forgotPasswordForm.value.account) {
    toast.error("请输入账号");
    return false;
  }

  if (!forgotPasswordForm.value.question) {
    toast.error("请选择安全问题");
    return false;
  }

  if (!forgotPasswordForm.value.answer) {
    toast.error("请输入安全答案");
    return false;
  }

  return true;
};

// 公共功能
defineExpose({
  openDialog,
  closeDialog,
});
</script>

<template>
  <div v-if="visible" class="dialog-container">
    <div class="dialog-backdrop" @click.self="closeDialog"></div>

    <!-- 登录对话框 -->
    <div v-if="currentType === 'login'" class="dialog">
      <button class="close-button" @click="closeDialog">×</button>
      <div class="dialog-header">登录</div>

      <div class="form-group">
        <label for="account">账户<span class="required">*</span></label>
        <input
          id="account"
          v-model="loginForm.account"
          type="text"
          placeholder="由字母、数字、下划线组成"
          class="input-field"
        />
      </div>

      <div class="form-group">
        <label for="password">密码<span class="required">*</span></label>
        <input
          id="password"
          v-model="loginForm.password"
          type="password"
          placeholder="由字母、数字、常用符号组成"
          class="input-field"
        />
      </div>

      <button :disabled="loading" class="submit-button" @click="handleLogin">
        <span v-if="loading">登录中...</span>
        <span v-else>登录</span>
      </button>

      <div class="dialog-footer">
        <span class="link-button" @click="currentType = 'forgot-password'"
          >忘记密码?</span
        >
        <span class="link-button" @click="currentType = 'register-intro'"
          >注册</span
        >
      </div>
    </div>

    <!-- 注册介绍对话框 -->
    <div v-if="currentType === 'register-intro'" class="dialog">
      <button class="close-button" @click="closeDialog">×</button>
      <div class="dialog-header">注册</div>

      <div class="content-box">
        <p>
          会员是医信提供的增值服务，注册后会自动继承当前游客信息。注册后将为您提供语音、视频、好友、红包提现、跨设备使用等高级功能，使得聊天体验得到整体的提升，平台不会收集和使用您的任何个人信息请放心注册，注意会员并不包含任何VIP特权。注册后觉得会员对您有用请在下一年度续费使用(68元/年)。如果您不想付费完全可以继续使用访客模式，谢谢你的支持和理解，我们将继续为您提供优质的服务！
        </p>
      </div>

      <button class="continue-button" @click="currentType = 'register-form'">
        继续注册→
      </button>
    </div>

    <!-- 注册表单对话框 -->
    <div v-if="currentType === 'register-form'" class="dialog">
      <button class="close-button" @click="closeDialog">×</button>
      <div class="dialog-header">注册</div>

      <!-- 昵称输入框（新增） -->
      <div class="form-group">
        <label for="reg-nickname">昵称<span class="required">*</span></label>
        <input
          id="reg-nickname"
          v-model="registerForm.nickname"
          type="text"
          placeholder="请输入您的昵称"
          class="input-field"
        />
      </div>

      <div class="form-group">
        <label for="reg-account">账户<span class="required">*</span></label>
        <input
          id="reg-account"
          v-model="registerForm.account"
          type="text"
          placeholder="由字母、数字、下划线组成"
          class="input-field"
        />
      </div>

      <div class="form-group">
        <label for="reg-password">密码<span class="required">*</span></label>
        <input
          id="reg-password"
          v-model="registerForm.password"
          type="password"
          placeholder="由字母、数字、常用符号组成"
          class="input-field"
        />
      </div>

      <div class="form-group">
        <label for="reg-confirm-password"
          >重密<span class="required">*</span></label
        >
        <input
          id="reg-confirm-password"
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="由字母、数字、常用符号组成"
          class="input-field"
        />
      </div>

      <button :disabled="loading" class="submit-button" @click="handleRegister">
        <span v-if="loading">注册中...</span>
        <span v-else>注册</span>
      </button>
    </div>

    <!-- 忘记密码对话框 -->
    <div v-if="currentType === 'forgot-password'" class="dialog">
      <button class="close-button" @click="closeDialog">×</button>
      <div class="dialog-header">忘记密码?</div>

      <div class="form-group">
        <label for="forgot-account">账户<span class="required">*</span></label>
        <input
          id="forgot-account"
          v-model="forgotPasswordForm.account"
          type="text"
          placeholder="由字母、数字、下划线组成"
          class="input-field"
        />
      </div>

      <div class="form-group">
        <label for="security-question"
          >安全问题<span class="required">*</span></label
        >
        <select
          id="security-question"
          v-model="forgotPasswordForm.question"
          class="select-field"
        >
          <option
            v-for="(question, index) in securityQuestions"
            :key="index"
            :value="question"
          >
            {{ question }}
          </option>
        </select>
      </div>

      <div class="form-group">
        <label for="security-answer"
          >安全答案<span class="required">*</span></label
        >
        <input
          id="security-answer"
          v-model="forgotPasswordForm.answer"
          type="text"
          placeholder="请输入安全答案"
          class="input-field"
        />
      </div>

      <button
        :disabled="loading"
        class="submit-button"
        @click="handleForgotPassword"
      >
        <span v-if="loading">验证中...</span>
        <span v-else>验证</span>
      </button>
    </div>
  </div>
</template>

<style scoped>
.dialog-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(3px);
}

.dialog {
  position: relative;
  width: 90%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1001;
}

.close-button {
  position: absolute;
  top: 12px;
  right: 12px;
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-button:hover {
  color: #333;
}

.dialog-header {
  font-size: 24px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.required {
  color: #ff4d4f;
}

.input-field {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}

.input-field:focus {
  border-color: #1890ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.select-field {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23333' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 10px center;
  background-size: 14px;
}

.select-field:focus {
  border-color: #1890ff;
  outline: none;
}

.submit-button {
  width: 100%;
  padding: 14px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s;
}

.submit-button:hover {
  background: #40a9ff;
}

.submit-button:disabled {
  background: #bae7ff;
  cursor: not-allowed;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.link-button {
  color: #1890ff;
  font-size: 14px;
  cursor: pointer;
  text-decoration: underline;
}

.link-button:hover {
  color: #40a9ff;
}

.content-box {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  max-height: 300px;
  overflow-y: auto;
}

.continue-button {
  display: block;
  width: 100%;
  padding: 14px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  text-align: center;
  cursor: pointer;
  text-decoration: none;
  transition: background 0.3s;
}

.continue-button:hover {
  background: #40a9ff;
}
</style>
